package org.cloud.framework.utils;

import java.io.File;  
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import javax.xml.transform.OutputKeys;  
import javax.xml.transform.Transformer;  
import javax.xml.transform.sax.SAXTransformerFactory;  
import javax.xml.transform.sax.TransformerHandler;  
import javax.xml.transform.stream.StreamResult;

import org.apache.commons.lang.StringEscapeUtils;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.AttributesImpl;  
  
public class CreateXMLFile {  
  
  
    public static void main(String[] args) throws Exception {
    	List<String> list = new ArrayList<String>();
    	list.add("title");
    	list.add("summery");
    	list.add("keyword");
    	list.add("author");
    	List<Map<String, Object>> mapList = new ArrayList<Map<String,Object>>();
    	Map<String, Object> m = new HashMap<String, Object>();
    	for (int i = 0; i < 50; i++) {
    		m = new HashMap<String, Object>();
    		m.put("title", "title"+i);
    		m.put("summery", "summery\r "+i);
    		m.put("keyword", "进化论学说在新中国的传播研究——以   《人民日报》(1948-2009)为例&& 	&& 	&& 	&& 	&& 	&& 	&& 	&& 	&& 	&&"+i);
    		m.put("author", "author"+i);
    		mapList.add(m);
    		if(i%10000==0){
    			System.out.println("==========="+i);
    		}
		}
    }
  
    @SuppressWarnings("resource")
	public static TransformerHandler createXML(FileOutputStream out) {
        try {
            // 创建工厂  
            SAXTransformerFactory factory = (SAXTransformerFactory) SAXTransformerFactory.newInstance();
            TransformerHandler handler = factory.newTransformerHandler();
            Transformer info = handler.getTransformer();
            // 是否自动添加额外的空白 
            info.setOutputProperty(OutputKeys.INDENT, "yes");
            // 设置字符编码  
            info.setOutputProperty(OutputKeys.ENCODING, "utf-8");
            info.setOutputProperty(OutputKeys.VERSION, "1.0");
            // 保存创建的saxbooks.xml  
            //FileOutputStream out = new FileOutputStream(new File(path));
            StreamResult result = new StreamResult(out);
            handler.setResult(result);
            handler.startElement("", "", "entities", null);
           return handler;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
    public static void writeToXml(TransformerHandler handler,List<Map<String, Object>>mapList) {
    	try {
    		 // 开始xml  
            handler.startDocument();
            //AttributesImpl impl = new AttributesImpl();
            //impl.clear();
            for (int i = 0; i < mapList.size(); i++) {
            	//impl.clear(); //清空属性  
    			handler.startElement("", "", "entity", null);
    			Map<String, Object> map = mapList.get(i);
    			
    			for (String key : map.keySet()) {
//    				impl.clear();
    				handler.startElement("", "", key, null);
    				if(map.get(key)!=null && !"".equals(map.get(key))){
    					String value = map.get(key).toString();
    					value = stripNonValidXMLChars(value);
//    					value = value.replace("<", "<![CDATA[<]]>").replace(">", "<![CDATA[>]]>")
//    							.replace("&", "<![CDATA[&]]>").replace("\n", "<![CDATA[\n]]>").replace("\r", "<![CDATA[\r]]>");//
    					value = "<![CDATA[" + value +"]]>";
    					handler.characters(value.toCharArray(), 0, value.length()); //为title元素添加文本  
    				}else if("".equals(map.get(key))){
    					handler.characters(" ".toCharArray(), 0, " ".length()); //为title元素添加文本  
    				}
    				handler.endElement("", "", key);
				}
    			handler.endElement("", "", "entity");
    			if(i%10000==0){
    				System.out.println("本组数据正在写入xml进度："+i+"/"+mapList.size());
    			}
    		}
            System.out.println("本组数据正在写入xml进度："+mapList.size()+"/"+mapList.size());
            
		} catch (Exception e) {
			e.printStackTrace();
		}
    }
	public static String stripNonValidXMLChars(String str) {
		if (str == null || "".equals(str)) {
			return str;
		}
		String s = "";
		char[] charArray = str.toCharArray();
		for (char c : charArray) {
			if (!(c < 0x9 || c > 0x9 && c < 0xA || c > 0xA && c < 0xD || c > 0xD && c  
					< 0x20 || c > 0xD7FF && c < 0xE000 || c > 0xFFFD)){//下面了允许的字符范围
				
				s += c;
			}
		}
		return s;
	}
    public static void closeXml(TransformerHandler handler,FileOutputStream out){
    	 try {
			handler.endElement("", "", "entities");
			handler.endDocument();
			out.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
    }
}  
